# -*- encoding:utf-8 -*-
import json
import translate
import time
from tqdm import tqdm
import re
from docx import Document
from docx.text.paragraph import Paragraph


def objects_to_json_file(objects, file_path):
    with open(file_path, 'w') as file:
        json.dump(objects, file)


def json_file_to_objects(file_path):
    with open(file_path, 'r') as file:
        return json.load(file)


def checkNameValid(name=None):
    """
    检测Windows文件名称！
    """
    if name is None:
        print("name is None!")
        return
    reg = re.compile(r'[\\/:*?"<>|\r\n]+')
    valid_name = reg.findall(name)
    if valid_name:
        for nv in valid_name:
            name = name.replace(nv, "_")
    return name


class TranslateWordTypePaper:

    def __init__(self, filename):
        self.filename = filename
        self.document = Document(filename)
        self.translateTool = translate.TranslateTool()

    @staticmethod
    def need_translate(text: str):
        return len(text) > 10 and not text.startswith("Authorized licensed use limited")

    def translate(self, translated_path):
        """
        使用百度翻译将word中的段落翻译为中文
        :type translated_path: object
        :return:
        """
        assert translated_path is not None, "translated_path is not None"
        name = os.path.basename(self.filename)
        translated_document = Document()
        with tqdm(desc=name[:len(name) if len(name) < 50 else 50], total=len(self.document.paragraphs)) as t:
            for paragraph in self.document.paragraphs:
                # try:
                text = paragraph.text
                if len(text) >= 10 and text[:10].lower().find("refere") > 0:
                    break
                if self.need_translate(text):
                    translated_text = self.translateTool.translate(text, funcs=[self.translateTool.baidu_translate])
                    paragraph.text = translated_text
                    translated_document.add_paragraph(translated_text, paragraph.style)
                elif text.startswith("Authorized licensed use limited"):
                    paragraph.text = ''
                t.update(1)
            # except Exception as e:
            #     print("e :{}".format(e))
        self.document.save(translated_path)
        translated_document.save(translated_path[:translated_path.rindex(".docx")] + "_unformatted.docx")


if __name__ == '__main__':
    translate_path = r"E:\paper\AICITY"
    translated_path = r"E:\paper\translated2"
    import os

    if not os.path.exists(translated_path):
        os.mkdir(translated_path)
    for c_root, c_dirs, c_files in os.walk(translate_path):
        for file in c_files:
            if file.endswith('.docx'):
                translated_file = file[:file.rindex(".docx")] + "_translated.docx"
                file_path = os.path.join(c_root, file)
                translated_file_path = os.path.join(translated_path, translated_file)
                if not os.path.exists(translated_file_path):
                    translate_paper = TranslateWordTypePaper(file_path)
                    translate_paper.translate(translated_file_path)
